<template>
    <div class="page-container">
      <div class="page-section">
        <!-- 一、顶部统计概览 -->
        <el-row gutter="20" class="mb-6" style="margin-bottom: 15px;">
          <el-col :span="6" v-for="card in stats" :key="card.title">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon">
                  <i :class="card.icon"></i>
                </div>
                <div>
                  <div class="stat-value">{{ card.value }}</div>
                  <div class="stat-title">{{ card.title }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
  
        <!-- 二、图表展示区域 -->
        <el-row gutter="20" class="mb-6">
          <!-- 商品分类统计 -->
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div class="chart-header">商品分类统计</div>
              <v-chart :option="categoryOptions" autoresize class="chart-container" />
            </el-card>
          </el-col>
  
          <!-- 生产厂家占比 -->
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <div class="chart-header">生产厂家占比</div>
              <v-chart :option="manufacturerOptions" autoresize class="chart-container" />
            </el-card>
          </el-col>
        </el-row>
  
        <!-- 三、原有药品信息管理功能 -->
        <el-card shadow="never">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-lg font-bold">药品信息管理</span>
              <el-button type="primary" @click="openForm()">添加药品</el-button>
            </div>
          </template>
  
          <!-- 搜索栏 -->
          <el-form :inline="true" :model="searchForm" class="mb-4">
            <el-form-item label="药品名称">
              <el-input v-model="searchForm.name" placeholder="请输入药品名称" clearable @input="fetchData" />
            </el-form-item>
          </el-form>
  
          <!-- 表格展示 -->
          <el-table :data="drugList" border stripe>
            <el-table-column prop="name" label="药品名称" />
            <el-table-column prop="category" label="分类" width="120" />
            <el-table-column prop="dosage" label="推荐剂量" />
            <el-table-column prop="frequency" label="推荐频次" />
            <el-table-column prop="price" label="单价（元）" />
            <el-table-column prop="manufacturer" label="生产厂家" />
            <el-table-column prop="description" label="药品描述" show-overflow-tooltip />
            <el-table-column label="创建时间">
              <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="openForm(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteDrug(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
  
          <!-- 分页 -->
          <el-pagination
            class="mt-4"
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
            background
          />
        </el-card>
  
        <!-- 四、添加 / 编辑 弹窗 -->
        <el-dialog v-model="dialogVisible" :title="formData.id ? '编辑药品' : '添加药品'" width="600px">
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
            <el-form-item label="药品名称" prop="name">
              <el-input v-model="formData.name" />
            </el-form-item>
            <el-form-item label="分类" prop="category">
              <el-input v-model="formData.category" />
            </el-form-item>
            <el-form-item label="推荐剂量" prop="dosage">
              <el-input v-model="formData.dosage" />
            </el-form-item>
            <el-form-item label="推荐频次" prop="frequency">
              <el-input v-model="formData.frequency" />
            </el-form-item>
            <el-form-item label="单价" prop="price">
              <el-input v-model="formData.price" type="number" />
            </el-form-item>
            <el-form-item label="生产厂家" prop="manufacturer">
              <el-input v-model="formData.manufacturer" />
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input v-model="formData.description" type="textarea" :rows="3" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </template>
        </el-dialog>
      </div>
  
      <!-- 悬浮按钮 -->
      <div
        class="floating-button"
        :style="{ top: dragPosition.top + 'px', left: dragPosition.left + 'px' }"
        @mousedown="startDrag"
        @click="handleFloatingClick"
      >
        💡AI
      </div>
  
      <!-- AI 对话框 -->
      <el-dialog v-model="aiDialogVisible" title="AI 药品助手" width="600px">
        <el-input
          v-model="aiQuestion"
          placeholder="请输入你要咨询的问题，比如用法、副作用等"
          type="textarea"
          :rows="3"
        />
        <el-button type="primary" class="mt-2" @click="askAi">发送</el-button>
  
        <div v-if="aiAnswer" class="mt-4">
          <b>AI 回复：</b>
          <div style="white-space: pre-wrap;">{{ aiAnswer }}</div>
        </div>
  
        <template #footer>
          <el-button @click="aiDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import axios from 'axios'
  import dayjs from 'dayjs'
  // ECharts
  import VChart from 'vue-echarts'
  import { use } from 'echarts/core'
  import { CanvasRenderer } from 'echarts/renderers'
  import { PieChart } from 'echarts/charts'
  import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'
  import request from '@/utils/request'

  use([CanvasRenderer, PieChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent])

  // 统计卡片数据
  const stats = reactive([
    { title: '总药品数', value: 0, icon: 'el-icon-s-operation' },
    { title: '平均单价', value: '0 元', icon: 'el-icon-price-tag' },
    { title: '最高单价', value: '0 元', icon: 'el-icon-star-on' },
    { title: '最低单价', value: '0 元', icon: 'el-icon-star-off' }
  ])

  // 商品分类统计（饼图配置）
  const categoryOptions = ref({
    title: { text: '商品分类统计', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: {
      orient: 'vertical',
      left: '5%',
      top: 'center',
      itemGap: 8,
      textStyle: { fontSize: 12 }
    },
    series: [{
      type: 'pie',
      radius: '50%',
      center: ['75%', '50%'],
      data: [],
      emphasis: {
        itemStyle: { shadowBlur: 10, shadowOffsetX: 0 }
      },
      label: { show: true },
      labelLine: { show: true }
    }]
  })

  // 生产厂家占比
  const manufacturerOptions = ref({
    title: { text: '生产厂家占比', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: {
      orient: 'vertical',
      left: '5%',
      top: 'center',
      itemGap: 8,
      textStyle: { fontSize: 12 }
    },
    series: [{
      type: 'pie',
      radius: '50%',
      center: ['75%', '50%'],
      data: [],
      emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0 } },
      label: { show: true },
      labelLine: { show: true }
    }]
  })

  const formatDate = val => (val ? dayjs(val).format('YYYY-MM-DD') : '-')

  // 搜索 & 分页 & 列表
  const searchForm = reactive({ name: '' })
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const drugList = ref([])

  async function fetchData() {
    try {
      const res = await request.get('/api/medicine/info/list', {
        params: { page: currentPage.value, pageSize: pageSize.value, name: searchForm.name }
      })
      drugList.value = res.data
      total.value = res.total
    } catch {
      ElMessage.error('获取药品信息失败')
    }
  }

  async function fetchStats() {
    try {
      const res = await request.get('/api/medicine/info/stats')
      const d = res
      stats[0].value = d.totalCount
      stats[1].value = `${d.avgPrice} 元`
      stats[2].value = `${d.maxPrice} 元`
      stats[3].value = `${d.minPrice} 元`
    } catch {
      ElMessage.error('获取统计数据失败')
    }
  }

  async function fetchChartData() {
    try {
      // 分类统计
      const catRes = await request.get('/api/medicine/info/category-stats')
      categoryOptions.value.series[0].data = catRes.map(item => ({
        name: item.category,
        value: item.count
      }))

      // 厂家占比
      const ratio = await request.get('/api/medicine/info/manufacturer-ratio')
      manufacturerOptions.value.series[0].data = ratio.map(item => ({
        name: item.name,
        value: item.count
      }))
    } catch {
      ElMessage.error('获取图表数据失败')
    }
  }

  function handlePageChange(page) {
    currentPage.value = page
    fetchData()
  }

  // 弹窗 & 表单
  const dialogVisible = ref(false)
  const formRef = ref()
  const formData = reactive({
    id: null, name: '', category: '', dosage: '',
    frequency: '', price: '', manufacturer: '', description: ''
  })
  const rules = {
    name: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
    price: [{ required: true, message: '请输入单价', trigger: 'blur' }]
  }

  function openForm(record = null) {
    Object.assign(formData, record || {
      id: null, name: '', category: '', dosage: '',
      frequency: '', price: '', manufacturer: '', description: ''
    })
    dialogVisible.value = true
  }

  async function submitForm() {
    formRef.value.validate(async valid => {
      if (!valid) return
      try {
        if (formData.id) {
          await request.put('/api/medicine/info/update', formData)
        } else {
          await request.post('/api/medicine/info/add', formData)
        }
        ElMessage.success(formData.id ? '更新成功' : '添加成功')
        dialogVisible.value = false
        await fetchAll()
      } catch {
        ElMessage.error('操作失败')
      }
    })
  }

  async function deleteDrug(id) {
    try {
      await ElMessageBox.confirm('确定删除该药品信息？', '提示', { type: 'warning' })
      await request.delete(`/api/medicine/info/delete/${id}`)
      ElMessage.success('删除成功')
      await fetchAll()
    } catch {
      ElMessage.info('已取消')
    }
  }

  async function fetchAll() {
    await Promise.all([fetchData(), fetchStats(), fetchChartData()])
  }

  // ———— AI & 拖拽功能 ————
  const aiDialogVisible = ref(false)
  const aiQuestion = ref('')
  const aiAnswer = ref('')

  async function askAi() {
    if (!aiQuestion.value) {
      ElMessage.warning('请输入你的问题')
      return
    }
    try {
      const res = await request.post(
        '/api/ai/ask',
        null,
        { params: { question: aiQuestion.value } }
      )
      aiAnswer.value = res.content || 'AI 暂无回答'
    } catch {
      ElMessage.error('请求失败')
    }
  }

  // 拖拽按钮
  const dragPosition = reactive({ top: 400, left: 1200 })
  let isDragging = false
  let hasDragged = false
  let offsetX = 0
  let offsetY = 0

  function startDrag(e) {
    isDragging = true
    hasDragged = false
    offsetX = e.clientX - dragPosition.left
    offsetY = e.clientY - dragPosition.top
    document.addEventListener('mousemove', onDragging)
    document.addEventListener('mouseup', stopDrag)
  }

  function onDragging(e) {
    if (isDragging) {
      dragPosition.left = e.clientX - offsetX
      dragPosition.top = e.clientY - offsetY
      hasDragged = true
    }
  }

  function stopDrag() {
    isDragging = false
    document.removeEventListener('mousemove', onDragging)
    document.removeEventListener('mouseup', stopDrag)
  }

  // 点击按钮才打开
  function handleFloatingClick() {
    if (!hasDragged) {
      aiDialogVisible.value = true
      aiQuestion.value = ''
      aiAnswer.value = ''
    }
  }

  onMounted(fetchAll)
</script>
  
  <style scoped>
  .page-container {
    position: relative;
  }

  .page-section {
    padding: 16px;
    background: #f5f7fa;
  }

  .stat-card {
    background: linear-gradient(135deg, #83a4d4, #b6fbff);
    color: #fff;
    border-radius: 12px;
  }

  .stat-content {
    display: flex;
    align-items: center;
  }

  .stat-icon {
    margin-right: 12px;
    font-size: 32px;
  }

  .stat-title {
    font-size: 14px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    line-height: 1;
  }

  .chart-card {
    padding: 16px;
    border-radius: 12px;
    background: #fff;
  }

  .chart-header {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
  }

  .chart-container {
    height: 200px;
  }

  .floating-button {
    position: fixed;
    width: 60px;
    height: 60px;
    background: #409eff;
    color: #fff;
    border-radius: 50%;
    text-align: center;
    line-height: 50px;
    cursor: grab;
    font-size: 20px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
    z-index: 999;
  }

  .floating-button:hover {
    background: #66b1ff;
  }

  .mt-2 {
    margin-top: 12px;
  }

  .mt-4 {
    margin-top: 20px;
  }
</style>